package com.relax.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioTest11_selector {
    public static void main(String[] args) throws IOException {

        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        ServerSocket socket = serverSocketChannel.socket();
        socket.bind(new InetSocketAddress(9999));

        /**
         * 把channel注册到selector'上,注册为"连接"
         */
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            int numbers = selector.select();
            System.out.println("numbers:" + numbers);
            Set<SelectionKey> keys = selector.selectedKeys();
            System.out.println("SelectionKey:" + keys);

            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                /** 获得连接*/
                if (selectionKey.isAcceptable()) {

                    ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    iterator.remove();/**必须移除*/
                    System.out.println("获得客户端连接:" + socketChannel);
                }
                if (selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    int byteRead = 0;
                    final ByteBuffer byteBuffer = ByteBuffer.allocate(5);
                    while (true) {
                        final int read = socketChannel.read(byteBuffer);
                        if (read == 0) {
                            break;
                        }
                        byteBuffer.flip();
                        socketChannel.write(byteBuffer);
                        byteRead += read;
                    }
                    System.out.println("读取:" + byteRead + ",来源于:" + socketChannel);
                    iterator.remove();/**必须移除*/
                }
            }

        }
    }
}
